var tar = document.getElementById('editor');
var target = document.getElementById('preview');
var stage = new Array(); 
var commit = new Array();
var result = new Array();

window.console.info("test for editor");
window.addEventListener('load', initPage, false);
window.addEventListener('resize', setWindow, false);
window.addEventListener('unload', quitPage, false);

function initPage(){
	setWindow();
	var draft = getCookies('draft');
	document.getElementById('editor').innerText = (draft ? draft : '');
	getText();
	setExport();
	return;
}

function quitPage(){
	var draft = document.getElementById('editor').innerText;
	setCookies('draft', draft, 30);
	return;
}

function setWindow(){
	var editor = document.getElementById('editor');
    editor.style.minHeight = (window.innerHeight - 20) + 'px';
	var preview = document.styleSheets[0].rules[3];
	preview.style.left = (window.innerWidth * 0.45 + 20) + 'px';
	preview.style.width = (window.innerWidth * 0.55 - 60) + 'px';
	return;
}

function setExport(){
	var x = document.getElementById('export');
	x.addEventListener('click', function(){
		var title = document.getElementsByTagName('h1')[0].innerHTML;
		x.download = (title ? (title+'.html') : 'output.html');
		x.href = "data:application/octet-stream," + encodeURIComponent(document.getElementById('preview').innerHTML);
	})
}

function newtest(){
	tar.addEventListener('keyup', getText, false)
}

function getText(){
	stage = tar.innerText.split(/\n{2,}/);
	if(!stage[stage.length-1]){
		stage.pop();
	}
	var x;
	if(!stage){
		commit = stage;
	} else {
		for(x in stage){
			if(!commit[x] || commit[x] != stage[x]){
				commit[x] = stage[x];
				transform(x);
			}
		}
	}
}

function transform(index){
	commit.length = stage.length;
	var htmlStringObj = new PatternCheck(commit[index]);
	result[index] = htmlStringObj.getResult();
	newPreview();
}

function newPreview(){
	result.length = commit.length;
	target.innerHTML = result.join('<br>');
	initHljs();
	return;
}

function initHljs(){
	var codes = document.getElementsByTagName('pre');
	for(var i = 0; i < codes.length; i ++){
		hljs.highlightBlock(codes[i]);
	}
}

function setCookies(name, value, expireDays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expireDays);
	document.cookie = name + '=' + escape(value) + (expireDays ? ';expires=' + exdate.toGMTString() : '');
}

function getCookies(name){
	if(document.cookie.length > 0){
		c_start = document.cookie.indexOf(name+'=');
		if(c_start != -1){
			c_start = c_start + name.length + 1;
			c_end = document.cookie.indexOf(';', c_start);
			if(c_end == -1){
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
}
newtest();
